package com.np.retrofit211demo1.retrofit;

import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class InterceptorHelper {
    public static String TAG = "Interceptor";

    /**
     * 日志拦截器
     */
    public static Interceptor getLogInterceptor() {
        //设置打印数据的级别
//        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
//            return new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT).setLevel(HttpLoggingInterceptor.Level.BODY);
//        }else {
//            return new CustomizableHttpLoggingInterceptor(new CustomizableHttpLoggingInterceptor.Logger() {
//                @Override
//                public void log(@NonNull String s) {
//                    com.wellhome.firstaidapp.utils.LogUtil.d("OkHttpClient", s);
//                }
//            }, true, true, 1000000L);
//        }
        return new MaxSizeLoggingInterceptor(MaxSizeLoggingInterceptor.Logger.DEFAULT).setLevel(MaxSizeLoggingInterceptor.Level.BODY);
    }

    /**
     * 特殊异常统一处理的拦截类
     *
     * @return
     */
    public static Interceptor getWellHomeExceptionInterceptor() {

        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                Response response;
                response = chain.proceed(request);

                Response.Builder builder = response.newBuilder();
                Response clone = builder.build();
                ResponseBody responseBody = clone.body();

                try {
                    //Token失效错误
                    if (responseBody != null) {
                        String string = responseBody.string();
                        if (string != null && (string.contains("Token失效") || string.contains("未授权"))) {
                            LiveDataCenter.setAccessToken(null);
                        }

                        responseBody = ResponseBody.create(responseBody.contentType(), string);
                        return response.newBuilder().body(responseBody).build();
                    }

                } catch (Exception e) {

                }

                return response;

            }
        };
    }

    /**
     * 重试拦截器
     *
     * @return
     */
    public static Interceptor getRetryInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                int maxRetry = 10;//最大重试次数
                int retryNum = 5;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

                Request request = chain.request();
                Response response = chain.proceed(request);
                while (!response.isSuccessful() && retryNum < maxRetry) {
                    retryNum++;
                    response = chain.proceed(request);
                }
                return response;
            }
        };
    }

    /**
     * 请求头拦截器
     *
     * @return
     */
    public static Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //在这里你可以做一些想做的事,比如token失效时,重新获取token
                //或者添加header等等

                Request originalRequest = chain.request();

                //get请求也需要传header,所以注释以下代码
//                if (null == originalRequest.body()) {
//                    return chain.proceed(originalRequest);
//                }

                //获取用户token
                String token = null;
                try {
                    token = LiveDataCenter.getAccessToken().getValue().getAccess_token();
                } catch (Exception e) {
                }

                if (TextUtils.isEmpty(token)) {
                    token = "";
                }

                //应用版本
                //String version = BuildConfig.VERSION_NAME;

                Request compressedRequest = originalRequest.newBuilder()
//                        .header("Content-Encoding", "gzip")
//                        .header("User-Agent", "OkHttp Headers.java")
//                        .addHeader("Accept", "application/json; q=0.5")
//                        .addHeader("Accept", "application/vnd.github.v3+json")
//                        .addHeader("Accept-Encoding", "identity")
                        //全局token
                        .header("Authorization", "Bearer " + token)
//                        .addHeader("version", version)
//                    .addHeader(Constants.WEB_TOKEN, webi_token)
                        .build();
                Response proceed = chain.proceed(compressedRequest);
                return proceed;
            }
        };
    }
}
